<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');

class Common {
	private $CI;
	
	function Common() {
		$this->CI = &get_instance();
	}
	
	// UBB Code parse and replace - plug-ins support in the future?
	function UBBCode($source_string, $allow_html = TRUE) {
		ini_set('pcre.backtrack_limit', 400000);
		ini_set('pcre.recursion_limit', 400000);
		
		$ss = $source_string;
		$html_matches = array();
		
		// extract [html] contents if allow html
		if($allow_html) {
			$patt = '/(\[html\])(.*?)(\[\/html\])/is';
			preg_match_all($patt, $ss, $html_matches);
		}
		
		$ss = htmlspecialchars($ss, ENT_COMPAT, 'UTF-8');
		
		// Deal with newlines, tabs and multiple spaces
		$ss = str_replace(array("\r\n", "\r", "\n"), '<br />', $ss);
		$ss = str_replace(array("\t", '  '), array('&nbsp; &nbsp; ', '&nbsp; '), $ss);
		
		// Add paragraph tag around post - TODO
/*		$ss = preg_replace('#<br />\s*?<br />(?!\s*<br />)#i', "</p><p>", $ss);
		$ss = '<p>' . $ss . '</p>';*/
		
		// fix RegExp replace error for catching $&, found @ 2004-09-07?
		$ss = str_replace('$', '&#036;', $ss);
		
		// URL 1: [url]http://www.sinzy.net/[/url]
		$patt = '/(\[url\])(\S+?)(\[\/url\])/is';
		$ss = preg_replace($patt, '<a href="$2" target="_blank">$2</a>', $ss);
		// URL 2: [url=http://www.sinzy.net/]四年左右[/url]
		$patt = '/(\[url=(\S+?)\])(.+?)(\[\/url\])/is';
		$ss = preg_replace($patt, '<a href="$2" target="_blank">$3</a>', $ss);
		// URL 3: (no pop-up) [url1=http://www.sinzy.net/]四年左右[/url1]
		$patt = '/(\[url1=(\S+?)\])(.+?)(\[\/url1\])/is';
		$ss = preg_replace($patt, '<a href="$2" target="_self">$3</a>', $ss);
		
		// E-mail 1: [email]webmaster@sinzy.net[/email]
		$patt = '/(\[email\])(\S+\@\S+?)(\[\/email\])/is';
		$ss = preg_replace($patt, '<a href="mailto:$2">$2</a>', $ss);
		// E-mail 2: [email=webmaster@sinzy.net]My E-mail[/email]
		$patt = '/(\[email=(\S+\@\S+?)\])(.+?)(\[\/email\])/is';
		$ss = preg_replace($patt, '<a href="mailto:$2">$3</a>', $ss);
		
		// Images: [img]http://www.sinzy.net/Images/Logo.jpg[/img], Require CSS class "limited"
		$patt = '/(\[img\])([^javascript:]\S+?)(\[\/img\])/is';
		$ss = preg_replace($patt, '<img class="limited" alt="" src="$2" style="border:0;" />', $ss);
		// Images Left: [imgl]http://www.sinzy.net/Images/Logo.jpg[/imgl]
		$patt = '/(\[imgl\])([^javascript:]\S+?)(\[\/imgl\])/is';
		$ss = preg_replace($patt, '<img class="limited" style="float:left;margin:0 0.5em 0.5em 0;border:0;" alt="" src="$2" />', $ss);
		// Images Right: [imgr]http://www.sinzy.net/Images/Logo.jpg[/imgr]
		$patt = '/(\[imgr\])([^javascript:]\S+?)(\[\/imgr\])/is';
		$ss = preg_replace($patt, '<img class="limited" style="float:right;margin:0 0 0.5em 0.5em;border:0;" alt="" src="$2" />', $ss);
		
		// Italic: [i]Italic[/i]
		$patt = '/(\[i\])(.+?)(\[\/i\])/is';
		$ss = preg_replace($patt, '<em>$2</em>', $ss);
		// Bold: [b]Bold[/b]
		$patt = '/(\[b\])(.+?)(\[\/b\])/is';
		$ss = preg_replace($patt, '<strong>$2</strong>', $ss);
		// Underline: [u]Underline[/u]
		$patt = '/(\[u\])(.+?)(\[\/u\])/is';
		$ss = preg_replace($patt, '<u>$2</u>', $ss);
		
		// Center: [center]Center[/center]
		$patt = '/(\[center\])(.+?)(\[\/center\])/is';
		$ss = preg_replace($patt, '<center>$2</center>', $ss);
		
		// Color: [color=red]Red Text[/color]. red || #f00 || #b0c4de
		$patt = '/(\[color=(\S+?)\])(.+?)(\[\/color\])/is';
		$ss = preg_replace($patt, '<span style="color:$2;">$3</span>', $ss);
		// Text Background Color: [bgcolor=red]Some Text[/bgcolor]
		$patt = '/(\[bgcolor=(\S+?)\])(.+?)(\[\/bgcolor\])/is';
		$ss = preg_replace($patt, '<span style="background-color:$2;">$3</span>', $ss);
		
		// Code: [code]code[/code]. Require CSS class "code"
		$patt = '/(\[code\])(.+?)(\[\/code\])/is';
		$ss = preg_replace($patt, '<div class="code"><code>$2</code></div>', $ss);
		
		// Quotation: [quote]Quoted Text[/quote]. Require CSS class "quote"
		$patt = '/(\[quote\])(.+?)(\[\/quote\])/is';
		$ss = preg_replace($patt, '<div class="quote"><blockquote>$2</blockquote></div>', $ss);
		
		// Flash: [flash width=320 height=240]...[/flash]
		$patt = '/(\[flash width=(\d+) height=(\d+)\])(\S+?)(\[\/flash\])/is';
		$ss = preg_replace($patt, '<object width="$2" height="$3"><param name="movie" value="$4" /><param name="wmode" value="transparent"></param><param name="quality" value="high" /><embed src="$4" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" type="application/x-shockwave-flash" width="$2" height="$3"></embed></object>', $ss);
		
		// Flash Video: [video width=320 height=240]...[/video]
		$patt = '/(\[video width=(\d+) height=(\d+)\])(\S+?)(\[\/video\])/is';
		$ss = preg_replace($patt, '<object width="$2" height="$3"><param name="movie" value="$4" /><param name="wmode" value="transparent"></param><param name="quality" value="high" /><embed src="$4" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" type="application/x-shockwave-flash" width="$2" height="$3"></embed></object>', $ss);
		
		// Flash Video with Default Size (425x350): [video]...[/video]
		$patt = '/(\[video\])(\S+?)(\[\/video\])/is';
		$ss = preg_replace($patt, '<object width="425" height="350"><param name="movie" value="$2" /><param name="wmode" value="transparent"></param><param name="quality" value="high" /><embed src="$2" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" type="application/x-shockwave-flash" width="425" height="350"></embed></object>', $ss);
		
		// JavaScript: [script]URL of script[/script]
		$patt = '/(\[script\])(\S+?)(\[\/script\])/is';
		$ss = preg_replace($patt, '<script type="text/javascript" src="$2"></script>', $ss);
		
		// Blue Baozi [bb1]. Absolute Image Path Here!!!
		$patt = '/(\[bb(\d+?)\])/is';
		$ss = preg_replace($patt, '<img alt="" src="/img/bbx/BB$2.gif" style="border:0;" />', $ss);
		
		// Remove [more] Tag
		$patt = '/\[more\]/is';
		$ss = preg_replace($patt, '', $ss);
		
		// Show "Add To del.icio.us" Link
		$patt = '/\[delicious\]/is';
		$ss = preg_replace($patt, "<br /><div><img src=\"http://images.del.icio.us/static/img/delicious.small.gif\" alt=\"del.icio.us\" /> <a href=\"http://del.icio.us/post\" onclick=\"window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title),'delicious','toolbar=no,width=700,height=400');return false;\">Add to del.icio.us!</a></div>", $ss);
		
		if($allow_html) {
			$patt = '/(\[html\])(.*?)(\[\/html\])/is';
			for($i = 0; $i < count($html_matches[2]); $i++) {
				$ss = preg_replace($patt, $html_matches[2][$i], $ss, 1);
			}
		}
		
		return $ss;
	}
	
	function HTMLEncode($source_string) {
		$ss = $source_string;
		$ss = htmlspecialchars($ss, ENT_COMPAT, 'UTF-8');
		// Deal with newlines, tabs and multiple spaces
		$ss = str_replace(array("\r\n", "\r", "\n"), '<br />', $ss);
		$ss = str_replace(array("\t", '  '), array('&nbsp; &nbsp; ', '&nbsp; '), $ss);
		// fix RegExp replace error for catching $&, found @ 04.9.7 - ?
		$ss = str_replace('$', '&#036;', $ss);
		
		return $ss;
	}
	
	function HTMLSpecChars($ss) {
		return htmlspecialchars($ss, ENT_COMPAT, 'UTF-8');
	}
	
	function SetCookie($cookie_key, $cookie_value, $days = 0) {
		$cookie = array(
			'name' => $cookie_key,
			'value' => $cookie_value,
			'expire' => 60 * 60 * 24 * $days
		);
		set_cookie($cookie);
	}
	
	function GetCookie($cookie_key) {
		return get_cookie($cookie_key);
	}
	
	function SetSession($session_key, $session_value) {
		$session_array = array($session_key => $session_value);
		$this->CI->session->set_userdata($session_array);
	}
	
	function GetSession($session_key) {
		return $this->CI->session->userdata($session_key);
	}
	
	function ClearSession() {
		$this->CI->session->sess_destroy();
	}
	
	// We use user_url outside, for nicer looking, but inside are also ids
	function GetBloggerID($blogger_uri) {
		if(is_numeric($blogger_uri)) {
			// just use blogger-id as uri (allowed for compatibility)
			$qry = $this->CI->db->query('SELECT `id` FROM `nt_bloggers` WHERE `id` = ?', array($blogger_uri));
			if($qry->num_rows() > 0) {
				return $qry->row()->id;
			} else {
				return 0;
			}
		} else {
			$qry = $this->CI->db->query('SELECT `id` FROM `nt_bloggers` WHERE `user_url` = ?', array($blogger_uri));
			if($qry->num_rows() > 0) {
				return $qry->row()->id;
			} else {
				return 0;
			}
		}
	}
	
	// We use user_url outside, for nicer looking, but inside are also ids
	function GetBloggerIDUserName($blogger_uri) {
		if(is_numeric($blogger_uri)) {
			// just use blogger-id as uri (allowed for compatibility)
			$qry = $this->CI->db->query('SELECT `id`, `user_name` FROM `nt_bloggers` WHERE `id` = ?', array($blogger_uri));
			if($qry->num_rows() > 0) {
				return $qry->row();
			} else {
				return NULL;
			}
		} else {
			$qry = $this->CI->db->query('SELECT `id`, `user_name` FROM `nt_bloggers` WHERE `user_url` = ?', array($blogger_uri));
			if($qry->num_rows() > 0) {
				return $qry->row();
			} else {
				return NULL;
			}
		}
	}
	
	function GetCurrentBloggerURI() {
		return $this->CI->uri->segment(1); // -_-
	}
	
	function Now() {
		$server_tz = $this->CI->config->item('ServerTimeZone');
		$client_tz = $this->CI->config->item('ClientTimeZone');
		$tz_diff = ($client_tz - $server_tz) * 3600;
		$date_format = 'Y-m-d H:i:s'; // yyyy-mm-dd
		return date($date_format, time() + $tz_diff);
	}
	
	function TimeDiff($str_earlier, $str_later) {
		$secs = strtotime($str_later) - strtotime($str_earlier);
		if($secs < 0) {
			throw new Exception('Seconds less than 0!');
		}
		if($secs < 60) {
			return $secs . ' 秒前';
		} elseif($secs < 60 * 60) {
			return floor($secs / 60) . ' 分钟前';
		} elseif($secs < 60 * 60 * 24) {
			return floor($secs / (60 * 60)) . ' 小时前';
		} elseif($secs < 60 * 60 * 24 * 3) {
			return floor($secs / (60 * 60 * 24)) . ' 天前';
		} else {
			return date('n/j/Y G:i', strtotime($str_earlier));
		}
	}
	
	function NicerTime($ori_time) {
		return date('n/j/Y G:i:s', strtotime($ori_time));
	}
	
	function MoreMode($source_string, $blogger_uri, $entry_uri, $more_link_text = '点此阅读全文...') {
		$rv = $source_string;
		$pos = mb_strpos(strtolower($rv), '[more]', 0, 'UTF-8');
		if(!$pos) {
			return $rv;
		} else {
			$rv = mb_substr($rv, 0, $pos, 'UTF-8');
			$rv .= "\r\n" . '[url1=' . base_url() . $blogger_uri . '/entry/' . $entry_uri . ']' . $more_link_text . '[/url1]';
		}
		return $rv;
	}
	
	// will be used?
	function GetBloggerIDByUserName($blogger_username) {
		$qry = $this->CI->db->query('SELECT `id` FROM `nt_bloggers` WHERE `user_name` = ?', array($blogger_username));
		if($qry->num_rows() > 0) {
			return $qry->row()->id;
		} else {
			return 0;
		}
	}
	
	function GetUserNameByID($blogger_id) {
		$qry = $this->CI->db->query('SELECT `user_name` FROM `nt_bloggers` WHERE `id` = ?', array($blogger_id));
		if($qry->num_rows() > 0) {
			return $qry->row()->user_name;
		} else {
			return '';
		}
	}
	
	// will be used?
	function GetBloggerURIByID($blogger_id) {
		$qry = $this->CI->db->query('SELECT `user_url` FROM `nt_bloggers` WHERE `id` = ?', array($blogger_id));
		if($qry->num_rows() > 0) {
			$uri = $qry->row()->user_url;
			if(is_null($uri)) {
				return $blogger_id;
			} else {
				return $uri;
			}
		} else {
			return '';
		}
	}
	
	function GetAvatarName($user_id) {
		$fn = $_SERVER['DOCUMENT_ROOT'] . 'img/avatars/avt_' . $user_id . '_48x48.jpg';
		if(file_exists($fn)) {
			return 'avt_' . $user_id . '_48x48.jpg';
		} else {
			return 'avt_-1_48x48.jpg';
		}
	}
	
	function GetBloggerByID($blogger_id) {
		$qry = $this->CI->db->query('SELECT * FROM `nt_bloggers` where `id` = ?', array($blogger_id));
		if($qry->num_rows() > 0) {
			return $qry->row();
		} else {
			return NULL;
		}
	}
}
?>
